package com.iflytek.aidemo.teacher;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iflytek.aidemo.R;
import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ClassInfo;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.Teacher;
import com.iflytek.aidemo.util.SessionManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Calendar;

/**
 * 老师端 - 成绩概览页
 * 顶部选择班级，展示班级题目总数与平均分，下面是学生列表，可进入详情。
 */
public class TeacherScoreOverviewActivity extends AppCompatActivity implements StudentScoreAdapter.OnStudentClickListener {

    private Spinner spClass;
    private TextView tvClassSummary;
    private RecyclerView rvStudents;
    private StudentScoreAdapter adapter;
    private EditText etDate;
    private Button btnQuery;
    private View btnTrend;

    private final List<String> classList = new ArrayList<>();
    private final List<ClassInfo> classInfos = new ArrayList<>();
    private final List<StudentScoreItem> currentStudents = new ArrayList<>();
    private Integer selectedClassId = null;
    private String selectedDate = null; // yyyy-MM-dd
    private final ApiService api = new ApiServiceImpl();

    // 来自统计页的回传参数（等待班级列表加载后应用）
    @Nullable private Integer pendingJumpClassId = null;
    @Nullable private String pendingJumpDate = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_score_overview);

        // 返回按钮
        View back = findViewById(R.id.btn_back);
        if (back != null) back.setOnClickListener(v -> finish());

        spClass = findViewById(R.id.sp_class);
        tvClassSummary = findViewById(R.id.tv_class_summary);
        rvStudents = findViewById(R.id.rv_students);
        etDate = findViewById(R.id.et_date);
        btnQuery = findViewById(R.id.btn_query);
        btnTrend = findViewById(R.id.btn_trend);

        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, classList);
        spClass.setAdapter(spinnerAdapter);

        rvStudents.setLayoutManager(new LinearLayoutManager(this));
        adapter = new StudentScoreAdapter(currentStudents, this);
        rvStudents.setAdapter(adapter);

        spClass.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position >= 0 && position < classInfos.size()) {
                    selectedClassId = classInfos.get(position).getClassId();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });

        // 日期选择器
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        selectedDate = String.format("%04d-%02d-%02d", year, month + 1, day);
        etDate.setText(selectedDate);
        etDate.setOnClickListener(v -> {
            DatePickerDialog dlg = new DatePickerDialog(this, (view, y, m, d) -> {
                selectedDate = String.format("%04d-%02d-%02d", y, m + 1, d);
                etDate.setText(selectedDate);
            }, year, month, day);
            dlg.show();
        });

        btnQuery.setOnClickListener(v -> doQuery());

        // 统计图跳转
        if (btnTrend != null) {
            btnTrend.setOnClickListener(v -> {
                if (selectedClassId == null || classInfos.isEmpty()) {
                    Toast.makeText(this, "请先选择班级", Toast.LENGTH_SHORT).show();
                    return;
                }
                String className = spClass.getSelectedItem() != null ? spClass.getSelectedItem().toString() : "班级";
                Intent intent = new Intent(this, ClassScoreTrendActivity.class);
                intent.putExtra("class_id", selectedClassId);
                intent.putExtra("class_name", className);
                startActivity(intent);
            });
        }

        // 加载老师的班级
        loadTeacherClasses(spinnerAdapter);

        // 处理从统计页回传的跳转参数（首次创建时）
        applyIncomingIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        applyIncomingIntent(intent);
    }

    private void applyIncomingIntent(Intent intent) {
        if (intent == null) return;
        if (intent.hasExtra("jump_class_id")) {
            pendingJumpClassId = intent.getIntExtra("jump_class_id", -1);
            if (pendingJumpClassId != null && pendingJumpClassId <= 0) pendingJumpClassId = null;
        }
        if (intent.hasExtra("jump_date")) {
            pendingJumpDate = intent.getStringExtra("jump_date");
            if (pendingJumpDate != null && !pendingJumpDate.isEmpty()) {
                selectedDate = pendingJumpDate;
                etDate.setText(pendingJumpDate);
            }
        }
        // 如果班级列表已经加载完成，可以立刻应用
        maybeApplyPendingJump();
    }

    private void maybeApplyPendingJump() {
        if ((pendingJumpClassId != null) && !classInfos.isEmpty()) {
            int index = -1;
            for (int i = 0; i < classInfos.size(); i++) {
                if (classInfos.get(i).getClassId() == pendingJumpClassId) { index = i; break; }
            }
            if (index >= 0) {
                spClass.setSelection(index);
                selectedClassId = classInfos.get(index).getClassId();
            }
        }
        if (pendingJumpDate != null && !pendingJumpDate.isEmpty()) {
            selectedDate = pendingJumpDate;
            etDate.setText(pendingJumpDate);
        }
        if (pendingJumpDate != null || pendingJumpClassId != null) {
            // 触发查询
            doQuery();
            pendingJumpClassId = null;
            pendingJumpDate = null;
        }
    }

    private void loadTeacherClasses(ArrayAdapter<String> spinnerAdapter) {
        new Thread(() -> {
            try {
                SessionManager sm = new SessionManager(this);
                String userId = sm.getCurrentUser() != null ? sm.getCurrentUser().getUserId() : null;
                ApiResponse<Teacher> response=api.gerTeacherIdByUserId(userId);
                String teacherId= response.getData().getTeacherId();
                System.out.println("teacherId:"+teacherId);
                ApiResponse<List<ClassInfo>> resp = api.getClassesByTeacher(teacherId == null ? "" : teacherId);
                runOnUiThread(() -> {
                    classList.clear();
                    classInfos.clear();
                    if (resp != null && resp.getCode() == 200 && resp.getData() != null) {
                        classInfos.addAll(resp.getData());
                        for (ClassInfo ci : classInfos) {
                            classList.add(ci.getClassName());
                        }
                        if (!classInfos.isEmpty()) {
                            selectedClassId = classInfos.get(0).getClassId();
                        }
                    }
                    spinnerAdapter.notifyDataSetChanged();
                    // 如果有等待应用的跳转参数，这里尝试应用
                    maybeApplyPendingJump();
                });
            } catch (Exception e) {
                runOnUiThread(spinnerAdapter::notifyDataSetChanged);
            }
        }).start();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void doQuery() {
        final Integer classId = selectedClassId;
        final String date = selectedDate != null ? selectedDate : etDate.getText().toString();
        if (classId == null) return;

        new Thread(() -> {
            ApiResponse<org.json.JSONObject> resp = api.getClassOverviewWithStudents(classId, date);
            runOnUiThread(() -> {
                try {
                    if (resp != null && resp.getCode() == 200 && resp.getData() != null) {
                        org.json.JSONObject data = resp.getData();
                        int totalCount = data.optInt("totalCount", 0);
                        int correctCount = data.optInt("correctCount", 0);
                        double averageRate = data.optDouble("averageRate", 0.0); // 0~1

                        String classNameShow = "班级";
                        if (spClass.getSelectedItem() != null) classNameShow = spClass.getSelectedItem().toString();
                        float avgPercent = (float) (averageRate * 100.0);
                        tvClassSummary.setText(String.format("%s  题目总数：%d  班级平均分：%.1f", classNameShow, totalCount, avgPercent));

                        org.json.JSONArray recordsOuterCheck = data.optJSONArray("records");
                        boolean noData = totalCount <= 0 || recordsOuterCheck == null || recordsOuterCheck.length() == 0;
                        if (noData) {
                            currentStudents.clear();
                            adapter.notifyDataSetChanged();
                            android.widget.Toast.makeText(this, "暂无完成记录", android.widget.Toast.LENGTH_SHORT).show();
                            return;
                        }

                        // 构建学生最新成绩列表：以 submitTime 最新的一条为准
                        currentStudents.clear();
                        Map<Integer, org.json.JSONObject> latestByStudent = new HashMap<>();
                        Map<Integer, String> latestTime = new HashMap<>();
                        org.json.JSONArray recordsOuter = data.optJSONArray("records");
                        if (recordsOuter != null) {
                            for (int i = 0; i < recordsOuter.length(); i++) {
                                org.json.JSONArray inner = recordsOuter.optJSONArray(i);
                                if (inner == null) continue;
                                for (int j = 0; j < inner.length(); j++) {
                                    org.json.JSONObject rec = inner.optJSONObject(j);
                                    if (rec == null) continue;
                                    int sid = rec.optInt("studentId");
                                    String time = rec.optString("submitTime", "");
                                    String prev = latestTime.get(sid);
                                    if (prev == null || time.compareTo(prev) >= 0) {
                                        latestTime.put(sid, time);
                                        latestByStudent.put(sid, rec);
                                    }
                                }
                            }
                        }

                        for (Map.Entry<Integer, org.json.JSONObject> e : latestByStudent.entrySet()) {
                            int sid = e.getKey();
                            org.json.JSONObject rec = e.getValue();
                            int c = rec.optInt("count", 0);
                            int cc = rec.optInt("countCorrect", 0);
                            org.json.JSONObject student=rec.optJSONObject("student");
                            float rate = c > 0 ? (cc * 100f / c) : 0f;
                            assert student != null;
                            String studentName = student.optString("studentName","student"+sid);
                            currentStudents.add(new StudentScoreItem(sid, studentName, rate));
                        }

                        adapter.notifyDataSetChanged();
                    } else {
                        android.widget.Toast.makeText(this, "查询失败", android.widget.Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception ignore) {}
            });
        }).start();
    }

    @Override
    public void onStudentClick(StudentScoreItem item) {
        Intent intent = new Intent(this, StudentScoreDetailActivity.class);
        intent.putExtra("student_id", item.getStudentId());
        intent.putExtra("student_name", item.getStudentName());
        intent.putExtra("date", selectedDate);
        startActivity(intent);
    }
}
